package com.example.newshomework

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import okhttp3.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.IOException

// 数据类
data class News(
    val title: String,
    val content: String,
    val publish_date: String,
    val id: String
)

// 适配器
class NewsAdapter(private val newsList: List<News>) : RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {
    class NewsViewHolder(val textView: android.widget.TextView) : RecyclerView.ViewHolder(textView)
    override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): NewsViewHolder {
        val tv = android.widget.TextView(parent.context)
        tv.setPadding(32, 32, 32, 32)
        tv.textSize = 16f
        return NewsViewHolder(tv)
    }
    override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
        holder.textView.text = newsList[position].title
    }
    override fun getItemCount() = newsList.size
}

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private val newsList = mutableListOf<News>()
    private val adapter = NewsAdapter(newsList)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        recyclerView = findViewById(R.id.newsRecyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
        fetchNews()
    }

    private fun fetchNews() {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url("http://127.0.0.1:8000/api/v1/news/")
            .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDg5NTMxOTEsInN1YiI6IjZiZjM4OTdjLWVlOTYtNGE5Yy05OTVjLTA0ZTkyNWM0YWU4ZCJ9.pjcpBmk0TEzjlXSJqg61N6A5VFetKk-6REcvcBVyXi4;")
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {}
            override fun onResponse(call: Call, response: Response) {
                response.body?.string()?.let { json ->
                    val type = object : TypeToken<List<News>>() {}.type
                    val list: List<News> = Gson().fromJson(json, type)
                    runOnUiThread {
                        newsList.clear()
                        newsList.addAll(list)
                        adapter.notifyDataSetChanged()
                    }
                }
            }
        })
    }
}